<template>
  <div class="settings">
    <div class="page-header">
      <h1>系统设置</h1>
    </div>
    
    <el-row :gutter="20">
      <!-- 左侧菜单 -->
      <el-col :span="6">
        <el-card>
          <el-menu
            :default-active="activeTab"
            class="settings-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="company">
              <el-icon><OfficeBuilding /></el-icon>
              <span>公司信息</span>
            </el-menu-item>
            <el-menu-item index="users">
              <el-icon><User /></el-icon>
              <span>用户管理</span>
            </el-menu-item>
            <el-menu-item index="roles">
              <el-icon><Lock /></el-icon>
              <span>角色权限</span>
            </el-menu-item>
            <el-menu-item index="logs">
              <el-icon><Document /></el-icon>
              <span>操作日志</span>
            </el-menu-item>
            <el-menu-item index="system">
              <el-icon><Setting /></el-icon>
              <span>系统配置</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      
      <!-- 右侧内容 -->
      <el-col :span="18">
        <el-card>
          <!-- 公司信息 -->
          <div v-if="activeTab === 'company'">
            <h3>公司信息</h3>
            <el-form
              ref="companyFormRef"
              :model="companyForm"
              :rules="companyRules"
              label-width="120px"
              style="max-width: 600px;"
            >
              <el-form-item label="公司名称" prop="name">
                <el-input v-model="companyForm.name" placeholder="请输入公司名称" />
              </el-form-item>
              <el-form-item label="公司简称" prop="shortName">
                <el-input v-model="companyForm.shortName" placeholder="请输入公司简称" />
              </el-form-item>
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="companyForm.phone" placeholder="请输入联系电话" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="companyForm.email" placeholder="请输入邮箱" />
              </el-form-item>
              <el-form-item label="公司地址" prop="address">
                <el-input v-model="companyForm.address" placeholder="请输入公司地址" />
              </el-form-item>
              <el-form-item label="公司简介" prop="description">
                <el-input
                  v-model="companyForm.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入公司简介"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveCompanyInfo">保存</el-button>
                <el-button @click="resetCompanyInfo">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 用户管理 -->
          <div v-if="activeTab === 'users'">
            <div class="section-header">
              <h3>用户管理</h3>
              <el-button type="primary" @click="showAddUserDialog = true">
                <el-icon><Plus /></el-icon>
                添加用户
              </el-button>
            </div>
            
            <el-table :data="userList" style="width: 100%">
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="realName" label="真实姓名" />
              <el-table-column prop="email" label="邮箱" />
              <el-table-column prop="role" label="角色" />
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                    {{ row.status === 'active' ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="创建时间" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="editUser(row)">
                    编辑
                  </el-button>
                  <el-button
                    :type="row.status === 'active' ? 'danger' : 'success'"
                    size="small"
                    @click="toggleUserStatus(row)"
                  >
                    {{ row.status === 'active' ? '禁用' : '启用' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 角色权限 -->
          <div v-if="activeTab === 'roles'">
            <div class="section-header">
              <h3>角色权限</h3>
              <el-button type="primary" @click="showAddRoleDialog = true">
                <el-icon><Plus /></el-icon>
                添加角色
              </el-button>
            </div>
            
            <el-table :data="roleList" style="width: 100%">
              <el-table-column prop="name" label="角色名称" />
              <el-table-column prop="description" label="角色描述" />
              <el-table-column prop="userCount" label="用户数" />
              <el-table-column prop="createdAt" label="创建时间" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="editRole(row)">
                    编辑权限
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteRole(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 操作日志 -->
          <div v-if="activeTab === 'logs'">
            <div class="section-header">
              <h3>操作日志</h3>
              <el-button @click="clearLogs">清空日志</el-button>
            </div>
            
            <el-row :gutter="20" style="margin-bottom: 20px;">
              <el-col :span="8">
                <el-input
                  v-model="logSearchKeyword"
                  placeholder="搜索用户或操作"
                  prefix-icon="Search"
                  clearable
                />
              </el-col>
              <el-col :span="8">
                <el-date-picker
                  v-model="logDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%"
                />
              </el-col>
              <el-col :span="8">
                <el-button type="primary" @click="searchLogs">搜索</el-button>
                <el-button @click="resetLogSearch">重置</el-button>
              </el-col>
            </el-row>
            
            <el-table :data="logList" style="width: 100%">
              <el-table-column prop="user" label="用户" />
              <el-table-column prop="action" label="操作" />
              <el-table-column prop="module" label="模块" />
              <el-table-column prop="ip" label="IP地址" />
              <el-table-column prop="createdAt" label="操作时间" />
            </el-table>
            
            <div class="pagination">
              <el-pagination
                v-model:current-page="logCurrentPage"
                v-model:page-size="logPageSize"
                :page-sizes="[10, 20, 50]"
                :total="logTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleLogSizeChange"
                @current-change="handleLogCurrentChange"
              />
            </div>
          </div>
          
          <!-- 系统配置 -->
          <div v-if="activeTab === 'system'">
            <h3>系统配置</h3>
            <el-form
              ref="systemFormRef"
              :model="systemForm"
              label-width="180px"
              style="max-width: 800px;"
            >
              <el-form-item label="系统名称">
                <el-input v-model="systemForm.systemName" placeholder="请输入系统名称" />
              </el-form-item>
              <el-form-item label="系统Logo">
                <el-upload
                  class="logo-upload"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeLogoUpload"
                >
                  <img v-if="systemForm.logo" :src="systemForm.logo" class="logo-preview" />
                  <el-icon v-else class="logo-upload-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="登录验证码">
                <el-switch v-model="systemForm.enableCaptcha" />
              </el-form-item>
              <el-form-item label="密码最小长度">
                <el-input-number v-model="systemForm.minPasswordLength" :min="6" :max="20" />
              </el-form-item>
              <el-form-item label="会话超时时间(分钟)">
                <el-input-number v-model="systemForm.sessionTimeout" :min="30" :max="480" />
              </el-form-item>
              <el-form-item label="文件上传大小限制(MB)">
                <el-input-number v-model="systemForm.maxFileSize" :min="1" :max="100" />
              </el-form-item>
              <el-form-item label="系统维护模式">
                <el-switch v-model="systemForm.maintenanceMode" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveSystemConfig">保存配置</el-button>
                <el-button @click="resetSystemConfig">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="showAddUserDialog"
      title="添加用户"
      width="500px"
    >
      <el-form
        ref="addUserFormRef"
        :model="addUserForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="addUserForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addUserForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="addUserForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="运营人员" value="operator" />
            <el-option label="财务人员" value="finance" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddUserDialog = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const activeTab = ref('company')
const showAddUserDialog = ref(false)
const showAddRoleDialog = ref(false)

// 公司信息
const companyForm = ref({
  name: '示例电商有限公司',
  shortName: '示例电商',
  phone: '400-123-4567',
  email: 'contact@example.com',
  address: '北京市朝阳区建国门外大街1号',
  description: '专业的电商ERP管理系统提供商'
})

const companyRules = {
  name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  shortName: [{ required: true, message: '请输入公司简称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 用户管理
const userList = ref([
  {
    id: 1,
    username: 'admin',
    realName: '管理员',
    email: 'admin@example.com',
    role: '管理员',
    status: 'active',
    createdAt: '2024-01-01'
  },
  {
    id: 2,
    username: 'zhangsan',
    realName: '张三',
    email: 'zhangsan@example.com',
    role: '运营人员',
    status: 'active',
    createdAt: '2024-01-15'
  },
  {
    id: 3,
    username: 'lisi',
    realName: '李四',
    email: 'lisi@example.com',
    role: '财务人员',
    status: 'inactive',
    createdAt: '2024-02-01'
  }
])

const addUserForm = ref({
  username: '',
  realName: '',
  email: '',
  password: '',
  role: ''
})

const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 角色权限
const roleList = ref([
  {
    id: 1,
    name: '管理员',
    description: '拥有系统所有权限',
    userCount: 1,
    createdAt: '2024-01-01'
  },
  {
    id: 2,
    name: '运营人员',
    description: '商品和订单管理权限',
    userCount: 3,
    createdAt: '2024-01-15'
  },
  {
    id: 3,
    name: '财务人员',
    description: '财务和报表权限',
    userCount: 2,
    createdAt: '2024-02-01'
  }
])

// 操作日志
const logSearchKeyword = ref('')
const logDateRange = ref([])
const logCurrentPage = ref(1)
const logPageSize = ref(10)
const logTotal = ref(100)

const logList = ref([
  {
    user: 'admin',
    action: '登录系统',
    module: '系统管理',
    ip: '192.168.1.100',
    createdAt: '2024-09-04 14:30:00'
  },
  {
    user: 'zhangsan',
    action: '添加商品',
    module: '商品管理',
    ip: '192.168.1.101',
    createdAt: '2024-09-04 13:15:00'
  },
  {
    user: 'lisi',
    action: '查看财务报表',
    module: '财务管理',
    ip: '192.168.1.102',
    createdAt: '2024-09-04 12:00:00'
  }
])

// 系统配置
const systemForm = ref({
  systemName: '电商ERP管理系统',
  logo: '',
  enableCaptcha: true,
  minPasswordLength: 8,
  sessionTimeout: 120,
  maxFileSize: 10,
  maintenanceMode: false
})

const handleMenuSelect = (index) => {
  activeTab.value = index
}

const saveCompanyInfo = () => {
  ElMessage.success('公司信息保存成功')
}

const resetCompanyInfo = () => {
  ElMessage.info('已重置公司信息')
}

const editUser = (user) => {
  console.log('编辑用户:', user)
}

const toggleUserStatus = (user) => {
  user.status = user.status === 'active' ? 'inactive' : 'active'
  ElMessage.success(`用户${user.status === 'active' ? '启用' : '禁用'}成功`)
}

const addUser = () => {
  ElMessage.success('用户添加成功')
  showAddUserDialog.value = false
}

const editRole = (role) => {
  console.log('编辑角色:', role)
}

const deleteRole = (role) => {
  ElMessage.success('角色删除成功')
}

const clearLogs = () => {
  ElMessage.success('日志已清空')
}

const searchLogs = () => {
  console.log('搜索日志:', logSearchKeyword.value, logDateRange.value)
}

const resetLogSearch = () => {
  logSearchKeyword.value = ''
  logDateRange.value = []
}

const handleLogSizeChange = (val) => {
  logPageSize.value = val
}

const handleLogCurrentChange = (val) => {
  logCurrentPage.value = val
}

const beforeLogoUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const saveSystemConfig = () => {
  ElMessage.success('系统配置保存成功')
}

const resetSystemConfig = () => {
  ElMessage.info('已重置系统配置')
}
</script>

<style scoped>
.settings {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
}

.settings-menu {
  border-right: none;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.logo-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.logo-upload:hover {
  border-color: #409eff;
}

.logo-preview {
  width: 100%;
  height: 100%;
  display: block;
}

.logo-upload-icon {
  font-size: 28px;
  color: #8